package cn.mrcode.wxsdk.core.dialogue.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuqiang
 * @version V1.0
 * @Description: ip工具
 * @date 2015/8/28 14:52
 */
public class IPUtil {
    private static Logger log = LoggerFactory.getLogger(IPUtil.class);
    private static ArrayList<String> cacheIpList = new ArrayList<>();
    private static Map<String, InetAddress> cacheIpMap = new HashMap<>();
    private static String loopIp = "127.0.0.1";

    public static String getRequestIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 获取本地所有的ip地址：比如在windows中使用ipconfig中显示出来的几个网卡ip,应该不包括回环ip
     * @param  filterEth0 是否过滤出 eth0 网卡地址
     * @return
     */
    private static void localAllIP(boolean filterEth0) {
        synchronized (loopIp) {
            if (cacheIpList.size() == 0) {
                return;
            }
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                    NetworkInterface intf = en.nextElement();
                    if(filterEth0 && !intf.getName().equals("eth0")){
                        continue;
                    }
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                            String ip = inetAddress.getHostAddress().toString();
                            log.debug("找到eth0的ip：" + ip);
                            cacheIpList.add(ip);
                            cacheIpMap.put(ip, inetAddress);
                        }
                    }
                }
            } catch (SocketException ex) {
                log.error("获取ip地址错误" + ex.getMessage() + ex.getStackTrace());
            }
        }
    }

    private static String getLocalAllIpFirst() {
        localAllIP(true);
        if(cacheIpList.size() > 0){
            String ip = cacheIpList.get(0);
            if (StringUtils.isNotBlank(ip)) {
                return ip;
            }
        }
        return null;
    }


    /**
     * 获取java api InetAddress 获取的默认ip地址
     */
    public static String getJavaApiDefaultIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            return null;
        }
    }

    /**
     * 获取本机ip地址：在当前服务器机器上所有网卡地址中，随机选择一个ip地址(不包括127.0.0.1)
     *
     * @return
     */
    public static String getLocalIP() {
        String javaApiDefaultIp = getJavaApiDefaultIp();

        if (StringUtils.isNotBlank(javaApiDefaultIp)) {
            if (!loopIp.equals(javaApiDefaultIp)) {
                return javaApiDefaultIp;
            }
        }
        return getLocalAllIpFirst();
    }

    public static String getHostName(){
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws UnknownHostException {
        String localIP = getLocalIP();
        System.out.println(localIP);
    }

}
